package org.hd.source.controller;

import org.hd.source.dto.LoginRequest;
import org.hd.source.dto.RegRequest;
import org.hd.source.dto.Result;
import org.hd.source.exception.BizException;
import org.hd.source.service.UserService;
import org.hd.source.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @PostMapping("/login")
    public Result login(@RequestBody @Valid LoginRequest request) {
        checkVerifyCode(request.getVerifyCode(), request.getUuid());
        return Result.SUCCESS().setData(userService.login(request.getUserName(), request.getPassword()));
    }

    @PostMapping("/reg")
    public Result reg(@RequestBody @Valid RegRequest regRequest) {
        checkVerifyCode(regRequest.getVerifyCode(), regRequest.getUuid());
        return Result.SUCCESS().setData(userService.register(regRequest));
    }

    private void checkVerifyCode(String verifyCode, String uuid) {
        if(!verifyCode.equalsIgnoreCase(redisUtils.get(uuid).toString())){
            throw new BizException("验证码错误！");
        }
    }
}
